package com.googlecode.bizyap.core.logging;

import java.util.logging.Level;


class JdkLoggerFactory extends LoggerFactory {

	protected Logger createLogger(String name) {
		return new JdkLogger(name);
	}

	private class JdkLogger implements Logger {
		private final java.util.logging.Logger logger;
		public JdkLogger(String name) {
			this.logger = java.util.logging.Logger.getLogger(name);
		}

		public boolean isDebugEnabled() {
			return logger.isLoggable(Level.FINE);
		}

		public boolean isErrorEnabled() {
			return logger.isLoggable(Level.SEVERE);
		}

		public boolean isInfoEnabled() {
			return logger.isLoggable(Level.INFO);
		}

		public boolean isWarnEnabled() {
			return logger.isLoggable(Level.WARNING);
		}

		public void debug(Object message) {
			log(Level.FINE, message, null);
		}

		public void debug(Object message, Throwable t) {
			log(Level.FINE, message, t);
		}

		public void info(Object message) {
			log(Level.INFO, message, null);
		}

		public void info(Object message, Throwable t) {
			log(Level.INFO, message, t);
		}

		public void warn(Object message) {
			log(Level.WARNING, message, null);
		}

		public void warn(Object message, Throwable t) {
			log(Level.WARNING, message, t);
		}

		public void error(Object message) {
			log(Level.SEVERE, message, null);
		}

		public void error(Object message, Throwable t) {
			log(Level.SEVERE, message, t);
		}
		
		 private void log(Level level, Object msg, Throwable ex) {
	        if (logger.isLoggable(level)) {
	            // Hack (?) to get the stack trace.
	            Throwable dummyException = new Throwable();
	            StackTraceElement locations[] = dummyException.getStackTrace();
	            // Caller will be the third element
	            String cname = "unknown";
	            String method = "unknown";
	            if( locations != null && locations.length > 2) {
	                StackTraceElement caller = locations[2];
	                cname = caller.getClassName();
	                method = caller.getMethodName();
	            }
	            
	            if(ex==null) {
	                logger.logp(level, cname, method, String.valueOf(msg));
	            } else {
	                logger.logp(level, cname, method, String.valueOf(msg), ex);
	            }
	        }

	    }
	}
}
